import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import ProDescriptions from '@ant-design/pro-descriptions';
import { urllist, addRule, updateRule, removeRule } from '@/services/ant-design-pro/api';
/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */

const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    let r = await addRule({ ...fields });
    console.log('add result', r)
    hide();
    message.success('操作成功');
    return true;
  } catch (error) {
    hide();
    console.error('handleAdd', error);
    message.error('添加失败');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (record, actionRef) => {
  const hide = message.loading('正在删除');
  try {
    await removeRule(record);
    hide();
    message.success('删除成功');
    if (actionRef.current) actionRef.current.reload()
    return true;
  } catch (error) {
    hide();
    message.error('删除失败');
    return false;
  }
};

const TableList = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */

  const [showDetail, setShowDetail] = useState(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useState({});
  const [selectedRowsState, setSelectedRows] = useState([]);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns = [
    {
      title: '短链接',
      dataIndex: 'name',
      tip: '唯一链接',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            suo.pw/t.{dom}
          </a>
        );
      },
    },
    {
      title: '描述',
      dataIndex: 'des',
      valueType: 'textarea', search: false,
    },
    {
      title: '长链接',
      dataIndex: 'url',
      valueType: 'textarea', search: false,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'ltime',
      valueType: 'dateTime', search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>,
        <a key="subscribeAlert"
          onClick={() => {
            handleRemove(record, actionRef)
          }}>
          删除
        </a>,
      ],
    },
  ];

  const EditForm = () => {
    if (!createModalVisible) return (<></>)
    return <ModalForm
      title={'编辑'}
      width="400px"
      visible={createModalVisible}
      onVisibleChange={handleModalVisible}
      onFinish={async (value) => {
        const success = await handleAdd(value);
        if (success) {
          handleModalVisible(false);
          if (actionRef.current) actionRef.current.reload()
        }
      }}
    >
      <ProFormText
        rules={[
          {
            required: true,
            message: '短链接必填',
          },
        ]}
        placeholder={'短链接,如aaa'}
        width="md"
        name="name"
        initialValue={currentRow.name}
      />
      <ProFormText
        placeholder={'备注说明'}
        width="md"
        name="des"
        initialValue={currentRow.des}
      />
      <ProFormTextArea width="md" name="url" initialValue={currentRow.url} placeholder={'长链接'} />
    </ModalForm>
  }
  return (
    <PageContainer>
      <ProTable
        headerTitle={'链接列表'}
        actionRef={actionRef}
        rowKey="name"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              setCurrentRow({});
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 添加
          </Button>,
        ]}
        request={urllist}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <EditForm />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow({});
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
